#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define TYPE_EXPECTED 0xAA
#define MAX_MESSAGE_SIZE 512
#define MAX_PACKET_SIZE 60
#define MAX_PACKET_NUM ((MAX_MESSAGE_SIZE + (MAX_PACKET_SIZE - 1)) / MAX_PACKET_SIZE)

typedef struct
{
    uint8_t magic;
    uint8_t totalPackets;
    uint8_t currentPacketIndex;
    uint8_t packetLen;
    uint8_t data[0];
} Message;

typedef struct
{
    uint8_t magic;                  // T: 消息类型
    uint8_t totalPackets;           // L: 总包数
    uint8_t currentPacketIndex;     // 当前接收包的索引
    size_t receivedBytes;           // 已接收的字节数
    uint8_t data[MAX_MESSAGE_SIZE]; // 数据缓冲区
} MessageReceiver;
static MessageReceiver receiver;

static void processPacket(MessageReceiver *receiver, const uint8_t *packet, size_t size)
{
    Message *msg = (Message *)packet;
    if ((msg->magic == TYPE_EXPECTED) && (msg->totalPackets <= MAX_PACKET_NUM) && (msg->currentPacketIndex < msg->totalPackets) && (msg->packetLen <= MAX_PACKET_SIZE))
    {
        if (msg->currentPacketIndex == 0)
        {
            receiver->receivedBytes = 0;
        }
        if (receiver->receivedBytes + msg->packetLen < sizeof(receiver->data))
        {
            memcpy(&receiver->data[receiver->receivedBytes], msg->data, msg->packetLen);
            receiver->receivedBytes += msg->packetLen;
        }
        if (msg->totalPackets == (msg->currentPacketIndex + 1))
        {
            printf("receiver->data %s", receiver->data);
        }
    }
}

int main()
{
    printf("MAX_PACKET_NUM %d", MAX_PACKET_NUM);
    const uint8_t msg1[] = {0xAA, 0x03, 0x00, 0x04, 'T', 'E', 'S', 'T'};
    const uint8_t msg2[] = {0xAA, 0x03, 0x01, 0x04, 'D', 'A', 'T', 'A'};
    const uint8_t msg3[] = {0xAA, 0x03, 0x02, 0x02, '\r', '\n'};

    processPacket(&receiver, msg1, sizeof(msg1));
    processPacket(&receiver, msg2, sizeof(msg2));
    processPacket(&receiver, msg3, sizeof(msg3));

    return 0;
}